<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;
use think\exception\PDOException;
use Exception;
use think\Db;

/**
 * 供应商
 *
 * @icon fa fa-circle-o
 */
class Supplier extends Backend
{

    /**
     * Supplier模型对象
     * @var \app\common\model\Depot\Supplier
     */
    protected $model = null;

    /**
     * 是否是关联查询
     */
    protected $relationSearch = true;

    /**
     * 快速搜索
    */
    protected $searchFields = ['name','provinces.name','citys.name','districts.name'];


    public function _initialize()
    {
        parent::_initialize();

        $this->model = new \app\common\model\Depot\Supplier;
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 供应商列表
    */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->with(['provinces','citys','districts'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        // 输出视图
        return $this->view->fetch();
    }
    
    /**
     * 添加供应商
    */
    public function add()
    {
        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            if(is_array($params) || !empty($params))
            {
                if(!empty($params['code']))
                {
                    $parentpath = model('Region')->where('code',$params['code'])->value('parentpath');

                    [$province,$city,$district] = explode(',',$parentpath);

                    $params['province'] = $province;

                    $params['city'] = $city;

                    $params['district'] = $district;
                }

                unset($params['code']);

                $result = $this->model->validate('common/Depot/Supplier')->save($params);

                if($result === FALSE)
                {
                    $this->error(__($this->model->getError()));
                }else{
                    $this->success();
                }
            }
        }

        return $this->view->fetch();
    }

    /**
     * 编辑供应商
     * 
     * @param String $ids 主键
     * 
     * @return String
    */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        // 找不到数据返回错误信息
        if(!$row)
        {
            $this->error(__('该供应商不存在，请重新选择'));
        }

        // 有接收POST提交
        if($this->request->isPost())
        {
            // 接收参数
            $params = $this->request->post('row/a');

            if(is_array($params) || !empty($params))
            {
                if(!empty($params['code']))
                {
                    $parentpath = model('Region')->where('code',$params['code'])->value('parentpath');

                    [$province,$city,$district] = explode(',',$parentpath);

                    $params['province'] = $province;

                    $params['city'] = $city;

                    $params['district'] = $district;
                }

                unset($params['code']);

                $params['id'] = $ids;

                $result = $this->model->validate('common/Depot/Supplier')->isUpdate(true)->save($params);

                if($result === FALSE)
                {
                    $this->error(__($this->model->getError()));
                }else{
                    $this->success();
                }
            }

        }

        // 赋值给模板使用的变量
        $data = [
            'row' => $row
        ];

        return $this->view->fetch('',$data);
    }

    /**
     * 删除供应商
     * 
     * @param String $ids 主键
    */
    public function del($ids = null)
    {
        $idArr = !empty($ids) ? explode(',',$ids) : [];

        if(empty($idArr))
        {
            $this->error(__('请选择需要删除供应商'));
        }

        $list = $this->model->where('id','in',$idArr)->select();

        $count = 0;

        // 开启事务
        Db::startTrans();

        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }

            // 提交事务
            Db::commit();

        } catch (PDOException|Exception $e) {
            // 事务回滚
            Db::rollback();

            // 获取错误信息
            $this->error($e->getMessage());
        }
        if ($count) {

            $this->success();
        }
    }
}